import { Point, toPoint } from "./Point";
export class Bounds {
  constructor(a, b) {
    if (!a) {
      return;
    }

    const points = b ? [a, b] : a;

    for (let i = 0, len = points.length; i < len; i++) {
      this.extend(points[i]);
    }
  }

  extend(obj) {
    let min2, max2;
    if (!obj) {
      return this;
    }

    if (obj instanceof Point || typeof obj[0] === "number" || "x" in obj) {
      min2 = max2 = toPoint(obj);
    } else {
      obj = toBounds(obj);
      min2 = obj.min;
      max2 = obj.max;

      if (!min2 || !max2) {
        return this;
      }
    }

    // @property min: Point
    // The top left corner of the rectangle.
    // @property max: Point
    // The bottom right corner of the rectangle.
    if (!this.min && !this.max) {
      this.min = min2.clone();
      this.max = max2.clone();
    } else {
      this.min.x = Math.min(min2.x, this.min.x);
      this.max.x = Math.max(max2.x, this.max.x);
      this.min.y = Math.min(min2.y, this.min.y);
      this.max.y = Math.max(max2.y, this.max.y);
    }
    return this;
  }

  // @method getCenter(round?: Boolean): Point
  // Returns the center point of the bounds.
  getCenter(round) {
    return toPoint(
      (this.min.x + this.max.x) / 2,
      (this.min.y + this.max.y) / 2,
      round
    );
  }

  getSize() {
    return this.max.subtract(this.min);
  }
}

export function toBounds(a, b) {
  if (!a || a instanceof Bounds) {
    return a;
  }
  return new Bounds(a, b);
}
